package com.netty;

import java.util.ArrayList;
import java.util.List;

import com.model.User;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
	
	// 构建user对象
	protected List<User> getUserList() {
		
		List<User> ulist = new ArrayList<User>();
		User user = new User();
		user.setId("001");
		user.setUsername("张三");
		user.setPassword("123456");
		user.setSex("男");
		user.setAge(29);
		user.setTelephone("13672451863");
		user.setAddress("广东省广州市天河区车陂大塘中街");
		
		User user2 = new User();
		user2.setId("002");
		user2.setUsername("李四");
		user2.setPassword("123456");
		user2.setSex("女");
		user2.setAge(27);
		user2.setTelephone("13612347654");
		user2.setAddress("广东省广州市越秀区东风东路701天誉商务大厦东塔1101");
		
		ulist.add(user);
		ulist.add(user2);
		
		return ulist;
	}
	
	/**
	 * 客户端与服务器端进行连接 可以发送数据
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("客户端与服务器端进行连接成功...");
		super.channelActive(ctx);
		List<User> ulist = getUserList();
		if(ulist != null && ulist.size() > 0) {
			ctx.writeAndFlush(ulist);
		}
	}
	
	// 客户端接收服务端返回信息
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		super.channelRead(ctx, msg);
		System.out.println("客户端接收服务端返回信息..." + msg);
	}
	
	/**
	 * 当Channel上的某个读操作完成时被调用
	 */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelReadComplete(ctx);
		System.out.println("客户端....channelReadComplete");
	}
	
	/**
	 * 处理过程中ChannelPipeline中发生错误时被调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, cause);
		System.out.println("client...发生异常...exceptionCaught..." + cause.getMessage());
		ctx.close();
	}
}
